<?php
namespace app\admin\controller;

use app\admin\service\NodeService;
use library\Controller;
use library\tools\Data;
use think\Console;
use think\Db;
use think\exception\HttpResponseException;

/**
 * 系统公共操作
 * Class Index
 * @package app\admin\controller
 */
class Index extends Controller
{
    protected $table_DB_Platform_Account_log_library = 'db_platform_log';       /*平台日志库*/
    protected $table_DB_Platform_Account_library = 'db_platform_accounts';      /*平台账户配置库*/
    protected $table_DB_Platform_Account_statistics = 'db_platform_statistics'; /*平台账户配置库*/
    protected $day_user_online = 'day_user_online';                             /* 在线用户统计 */
    protected $accounts_info = 'accounts_info';                                 /* 用户表 */
    protected $user_tradelog = 'tradelog';                                      /* 订单记录表 */
    protected $user_billing_info = 'billing_info';                              /* 计费点记录表 */
    protected $user_recharge_info = 'recharge_info';                            /* 充值情况记录表 */
    protected $user_data_info = 'data_info';                                    /* 日活记录表 */
    protected function Db_connect_day_user_online(){
         $day_user_online= Db::connect($this->table_DB_Platform_Account_log_library)->table($this->day_user_online);
         return $day_user_online;
    }
    protected function Db_connect_accounts_info(){
        $accounts_info= Db::connect($this->table_DB_Platform_Account_library)->table($this->accounts_info);
        return $accounts_info;
    }
    protected function Db_connect_user_billing_info(){
        $user_billing_info= Db::connect($this->table_DB_Platform_Account_statistics)->table($this->user_billing_info);
        return $user_billing_info;
    }
    protected function Db_connect_user_recharge_info(){
        $user_recharge_info= Db::connect($this->table_DB_Platform_Account_statistics)->table($this->user_recharge_info);
        return $user_recharge_info;
    }
    protected function Db_connect_user_data_info(){
        $user_recharge_info= Db::connect($this->table_DB_Platform_Account_statistics)->table($this->user_data_info);
        return $user_recharge_info;
    }
    protected function Db_connect_user_tradelog(){
        $user_tradelog= Db::connect($this->table_DB_Platform_Account_library)->table($this->user_tradelog);
        return $user_tradelog;
    }
    /**
     * 显示后台首页
     * @throws \ReflectionException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $this->title = '系统管理后台';
        NodeService::applyUserAuth(true);
        $this->menus = NodeService::getMenuNodeTree();
        if (!NodeService::islogin()) {
            $this->redirect('@admin/login');
        } else {
            $this->fetch();
        }
    }
    /**
     * 数据概览
     */
    public function main()
    {
        /*  今日新增用户  */
        $time=date('Y-m-d',time());
        $reg_user_today_count = $this->Db_connect_accounts_info()->where('RegisterDate','like',"%{$time}%")->count();
        $Diurnal_activity_user_today =$this->Db_connect_accounts_info()->where('LastLoginDate','like',"%{$time}%")->count();
        $today_recharge_amout= $this->Db_connect_user_data_info()->where('time',$time)->sum('recharge');
        $recharge_user_today =$this->Db_connect_user_data_info()->where('time',$time)->sum('recharge_count');
        $user_today_list =$this->Db_connect_user_data_info()->where('time',$time)->select();
        foreach ($user_today_list as $k => $v) {
            $channel_name = get_channel_name($v['channel_id']);
            $v['channel_name'] = $channel_name;
            $user_today_list[$k] = $v;
        }
        $this->assign('user_today_list',$user_today_list);
        $this->assign('recharge_user_today',$recharge_user_today);
        $this->assign('today_recharge_amout',$today_recharge_amout);
        $this->assign('reg_user_today_count',$reg_user_today_count);
        $this->assign('Diurnal_activity_user_today',$Diurnal_activity_user_today);
        $this->assign('user_billing_count',$this->user_billing_count());
        $this->assign('user_online_trend',$this->user_online_trend());
        $this->assign('user_recharge_info',$this->user_recharge_info());
        $this->assign('total_game_user_online_number',total_game_user_online_number());
        $this->fetch();
    }
    /* 平台日活分布情况 */
    public function Daily_activity_trend(){
        $arr =$this->Db_connect_user_data_info()->field('logincount,time')->group('time')->limit(7)->order('time desc')->select();
        $this->totalJson = ['count' => [], 'time' => []];
        foreach($arr as $value){
            $this->totalJson['count'][] =$this->Db_connect_user_data_info()->where('time',$value['time'])->sum('logincount');
            $this->totalJson['time'][]=$value['time'];
        }
        return $this->totalJson;
    }
    /* 计费点充值分布情况 */
    public function user_billing_count(){
        $time=date('Y-m-d',time());
        $where[] =['time','EQ',$time];
        $arr =$this->Db_connect_user_billing_info()->field('billingId,count')->where($where)->select();
        $this->totalJson = ['count' => [], 'billing' => []];
        foreach($arr as $value){
            $this->totalJson['count'][] = $value['count'];
            $this->totalJson['billing'][] = get_Billing_name($value['billingId']);
        }
        return $this->totalJson;
    }
    /* 渠道充值分布情况 */
    public function user_recharge_info(){
        $time=date('Y-m-d',time());
        $where[] =['time','EQ',$time];
        $arr =$this->Db_connect_user_recharge_info()->field('spreaderId,recharge')->where($where)->select();
        $this->totalJson = ['spreaderId' => [], 'recharge' => []];
        foreach($arr as $value){
            $this->totalJson['recharge'][] = $value['recharge'];
            if($value['spreaderId'] == 0) {$channel_name='官方-0-渠道';}else {$channel_name=get_channel_name($value['spreaderId']);}
            $this->totalJson['spreaderId'][] = $channel_name;
        }
        return $this->totalJson;
    }
    /* 实时在线人数走势 */
    public function user_online_trend(){
        $time=date('Y-m-d',time());
        /*开始时间当天零点*/
        $begin_time = strtotime(date('Y-m-d',time()));
        /*结束时间当天24点*/
        $end =$begin_time+24*3600;
        $arr =$this->Db_connect_day_user_online()->where('date','like',"%{$time}%")->select();
        $this->totalJson = ['count' => [], 'time' => []];
        for($i=$begin_time;$i<=$end;$i=$i+600){
            $date = date('Y-m-d H:i:s',$i);
            $this->totalJson['time'][] = $date;
        }
        foreach ($arr as $key => $value) {
            $this->totalJson['count'][] = $value['count'];
        }
        $end_time =$begin_time+24*3600+1;
        $end_count =$this->Db_connect_day_user_online()->where('date',date('Y-m-d H:i:s',$end_time))->value('count');
        array_push($this->totalJson['count'],$end_count);
        return $this->totalJson;
    }
    /**
     * 修改密码
     * @param integer $id
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function pass($id)
    {
        $this->applyCsrfToken();
        if (intval($id) !== intval(session('admin_user.id'))) {
            $this->error('只能修改当前用户的密码！');
        }
        if (!NodeService::islogin()) {
            $this->error('需要登录才能操作哦！');
        }
        if ($this->request->isGet()) {
            $this->verify = true;
            $this->_form('SystemUser', 'admin@user/pass', 'id', [], ['id' => $id]);
        } else {
            $data = $this->_input([
                'password'    => $this->request->post('password'),
                'repassword'  => $this->request->post('repassword'),
                'oldpassword' => $this->request->post('oldpassword'),
            ], [
                'oldpassword' => 'require',
                'password'    => 'require|min:4',
                'repassword'  => 'require|confirm:password',
            ], [
                'oldpassword.require' => '旧密码不能为空！',
                'password.require'    => '登录密码不能为空！',
                'password.min'        => '登录密码长度不能少于4位有效字符！',
                'repassword.require'  => '重复密码不能为空！',
                'repassword.confirm'  => '重复密码与登录密码不匹配，请重新输入！',
            ]);
            $user = Db::name('SystemUser')->where(['id' => $id])->find();
            if (md5($data['oldpassword']) !== $user['password']) {
                $this->error('旧密码验证失败，请重新输入！');
            }
            $result = NodeService::checkpwd($data['password']);
            if (empty($result['code'])) $this->error($result['msg']);
            if (Data::save('SystemUser', ['id' => $user['id'], 'password' => md5($data['password'])])) {
                $this->success('密码修改成功，下次请使用新密码登录！', '');
            } else {
                $this->error('密码修改失败，请稍候再试！');
            }
        }
    }

    /**
     * 修改用户资料
     * @param integer $id 会员ID
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function info($id = 0)
    {
        if (!NodeService::islogin()) {
            $this->error('需要登录才能操作哦！');
        }
        $this->applyCsrfToken();
        if (intval($id) === intval(session('admin_user.id'))) {
            $this->_form('SystemUser', 'admin@user/form', 'id', [], ['id' => $id]);
        } else {
            $this->error('只能修改登录用户的资料！');
        }
    }

    /**
     * 清理运行缓存
     * @auth true
     */
    public function clearRuntime()
    {
        if (!NodeService::islogin()) {
            $this->error('需要登录才能操作哦！');
        }
        try {
            Console::call('clear');
            Console::call('xclean:session');
            $this->success('清理运行缓存成功！');
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $e) {
            $this->error("清理运行缓存失败，{$e->getMessage()}");
        }
    }

    /**
     * 压缩发布系统
     * @auth true
     */
    public function buildOptimize()
    {
        if (!NodeService::islogin()) {
            $this->error('需要登录才能操作哦！');
        }
        try {
            Console::call('optimize:route');
            Console::call('optimize:schema');
            Console::call('optimize:autoload');
            Console::call('optimize:config');
            $this->success('压缩发布成功！');
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $e) {
            $this->error("压缩发布失败，{$e->getMessage()}");
        }
    }

}
